﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HWEngine;
using HWEngine.Generators;

namespace HandWriter.Controls
{
	public partial class FontsSelectionList : UserControl
	{
		private LetterSetRepository _fonts;

		[Category("Behavior")]
		public event EventHandler OnFontItemSelected;

		public string SelectedFontName { get; set; }

		private bool _initMode = false;

		public FontsSelectionList()
		{
			InitializeComponent();
		}

		public void SetFonts(LetterSetRepository fonts)
		{
			_initMode = true;
			_fonts = fonts;
			int oldIndex = listFonts.SelectedIndex;
			listFonts.DataSource = fonts.GetNames().ToList();

			//shift index if datasource is smaller then before
			if (oldIndex >= listFonts.Items.Count)
			{
				oldIndex = listFonts.Items.Count - 1;
			}

			listFonts.SelectedIndex = oldIndex;
			_initMode = false;
		}

		private void listFonts_DrawItem(object sender, DrawItemEventArgs e)
		{
			FontItemDrawHelper.DrawItem(sender, e, listFonts.Items.Cast<string>().ToList(), _fonts);
		}

		private void listFonts_DoubleClick(object sender, EventArgs e)
		{
			if (!_initMode)
			{
				int selectedIndex = listFonts.SelectedIndex;
				if (selectedIndex >= 0)
				{
					SelectedFontName = listFonts.Items[selectedIndex].ToString();
					if (OnFontItemSelected != null)
					{
						OnFontItemSelected.Invoke(sender, e);
					}
				}
			}
		}
	}
}
